<template>
  <div v-loading.fullscreen.lock="loading"

       element-loading-text="拼命计算中，CPU都冒烟了~"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <div style="margin: 10px 0">
      <el-input style="width: 200px" placeholder="请输入地址" suffix-icon="el-icon-search" v-model="address"></el-input>
      <el-button class="ml-5" type="primary" @click="query">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-popconfirm
          class="ml-5"
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="您确定批量删除这些数据吗？"
          @confirm="delBatch"
      >
        <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
      <el-button class="ml-5" type="danger" @click="openCompareDialogHandler">全表对比 <i
          class="el-icon-s-operation"></i></el-button>
      <el-select v-model="likePercent" placeholder="请选择相似率" class="ml-5">
        <el-option
            v-for="item in PercentList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>

    </div>

    <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="address" label="地址" align="center"></el-table-column>
      <el-table-column prop="addressCode" label="地址编码" width="150" align="center"></el-table-column>
      <el-table-column prop="createTime" label="添加时间" width="150" align="center"></el-table-column>
      <el-table-column prop="operator" label="添加人" width="150" align="center"></el-table-column>

      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)">查看相似率 <i class="el-icon-search"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="form.address ? form.address : '信息' " :visible.sync="dialogFormVisible" width="70%"
               :close-on-click-modal="false">
      <el-form label-width="120px" size="small" style="width: 80%; margin: 0 auto">
        <el-form-item label="地址">
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址编码">
          <el-input v-model="form.addressCode" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div v-if="sortCount"
           style="display: flex;grid-gap: 5px;margin-bottom: 10px;justify-content: center;align-items: center">
        <el-tag size="big" type="danger">大于90%数量：{{ sortCount['>90%'] }}</el-tag>
        <el-tag size="big" type="warning">大于80%数量：{{ sortCount['>80%'] }}</el-tag>
        <el-tag size="big" type="primary">大于70%数量：{{ sortCount['>70%'] }}</el-tag>
        <el-tag size="big" type="success">大于60%数量：{{ sortCount['>60%'] }}</el-tag>
        <el-tag size="big" type="info">大于50%数量：{{ sortCount['>50%'] }}</el-tag>
        <el-tag size="big" type="info">总数：{{ checkResult.length }}</el-tag>
        <el-select  v-model="likePercent" placeholder="请选择相似率" class="ml-5">
          <el-option
              v-for="item in PercentList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        <el-button type="warning" @click="exportToExcel">导出为Excel <i class="el-icon-upload2"></i> </el-button>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button @click="check" type="warning">计算相似度</el-button>
        <el-button type="primary" @click="save" :disabled="!hasChecked">确 定</el-button>
      </div>
      <div style="width: 100%;display: flex;justify-content: center;">
        <el-table v-if="checkResult" :data="checkResult" border stripe :header-cell-class-name="'headerBg'"
                  :default-sort="{prop: 'likePercent', order: 'descending'}"
                  @selection-change="handleSelectionChange">
          <el-table-column prop="compareAddress" label="对比地址" align="center"></el-table-column>
          <el-table-column prop="likePercent" label="相似率" width="110" align="center" sortable>
            <template slot-scope="scope">
              <el-tag size="small" :type="scope.row.likePercent > 0.9 ? 'danger'
           :scope.row.likePercent > 0.8 ? 'warning' : scope.row.likePercent > 0.7 ? 'primary'
            :scope.row.likePercent > 0.6 ? 'success' : 'info' ">{{ Math.floor(scope.row.likePercent * 100) }}%
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </el-dialog>

    <el-dialog title="全表对比" :visible.sync="isShowCompareDialog" width="30%"
               :close-on-click-modal="false">
      <div style="display: flex;flex-direction: column;align-items: center;font-size: 26px">
        <div>目前地址总数为：{{ addressCount }}</div>
        <div>全表对比操作会耗时较长</div>
        <div>执行后请耐心等待</div>
        <div>全表对比结果会保存在数据库中</div>
        <div>执行进度请在<span style="color: red">执行进度</span>中查看</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowCompareDialog = false">取 消</el-button>
        <el-button type="primary" @click="compare">执 行</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import * as XLSX from 'xlsx';
export default {
  name: "Address",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      name: "",
      form: {},
      dialogFormVisible: false,
      multipleSelection: [],
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      uploadHeaders: {"token": localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")).token : ''},
      isShowCompareDialog: false,
      addressCount: '',
      hasChecked: false,
      sortCount: {},
      checkResult: [],
      loading: false,
      address:'',
      PercentList:[
        {value: 0.5, label: '大于等于50%'},
        {value: 0.6, label: '大于等于60%'},
        {value: 0.7, label: '大于等于70%'},
        {value: 0.8, label: '大于等于80%'},
        {value: 0.9, label: '大于等于90%'},
        {value: 1, label: '100%'}
      ],
      likePercent:0.7
    }
  },
  created() {
    this.load()
  },
  methods: {
    exportToExcel() {
      if (this.checkResult.length === 0){
        this.$message.error("数据为空！")
        return

      }
      // 将数据转换为工作表
      const worksheet = XLSX.utils.json_to_sheet(this.checkResult);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      // 导出 Excel 文件
      XLSX.writeFile(workbook,  this.form.address +'.xlsx');
    },
    check() {
      if (!this.form.address) {
        this.$message.error("地址不能为空")
        return
      }
      this.loading = true
      this.form.likePercent = this.likePercent
      console.log(1)
      console.log(this.likePercent)
      this.request.post("/address/check", this.form).then(res => {
        this.checkResult = res.data
        this.sortCount = {'>50%': 0, '>60%': 0, '>70%': 0, '>80%': 0, '>90%': 0}
        for (let i = 0; i < this.checkResult.length; i++) {
          if (this.checkResult[i].likePercent > 0.9) {
            this.sortCount['>90%']++

          } else if (this.checkResult[i].likePercent >= 0.8) {
            this.sortCount['>80%']++
          } else if (this.checkResult[i].likePercent >= 0.7) {
            this.sortCount['>70%']++
          } else if (this.checkResult[i].likePercent >= 0.6) {
            this.sortCount['>60%']++
          } else if (this.checkResult[i].likePercent >= 0.5) {
            this.sortCount['>50%']++
          }
        }
        this.hasChecked = true
        this.loading = false
      })
    },
    openCompareDialogHandler() {
      this.request.get("/address/getAddressCount").then(res => {
        this.addressCount = res.data
        this.isShowCompareDialog = true
      })
    },
    compare() {
      this.request.get("/address/CompareWholeTable").then(res => {
        if (res.code === '0') {
          this.isShowCompareDialog = false
          this.$message.success("执行成功")
          this.$router.push("/compareTask")
        }
      })
    },
    load() {
      this.request.get("/address/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          address: this.address,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    reset() {
      this.pageNum = 1
      this.pageSize = 10
      this.address = ""
      this.load()
    },
    save() {
      this.request.post("/address", this.form).then(res => {
        if (res.code === '0') {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
        }
      })
    },
    handleAdd() {
      this.hasChecked = false
      this.dialogFormVisible = true
      this.checkResult = []
      this.sortCount = {}
      this.form = {}
    },
    handleEdit(row) {
      this.hasChecked = false
      this.checkResult = []
      this.sortCount = {}
      this.form = JSON.parse(JSON.stringify(row))
      this.loading = true
      this.form.likePercent = this.likePercent
      this.request.post("/address/check", this.form).then(res => {
        this.checkResult = res.data
        this.sortCount = {'>50%': 0, '>60%': 0, '>70%': 0, '>80%': 0, '>90%': 0}
        for (let i = 0; i < this.checkResult.length; i++) {
          if (this.checkResult[i].likePercent > 0.9) {
            this.sortCount['>90%']++

          } else if (this.checkResult[i].likePercent >= 0.8) {
            this.sortCount['>80%']++
          } else if (this.checkResult[i].likePercent >= 0.7) {
            this.sortCount['>70%']++
          } else if (this.checkResult[i].likePercent >= 0.6) {
            this.sortCount['>60%']++
          } else if (this.checkResult[i].likePercent >= 0.5) {
            this.sortCount['>50%']++
          }
        }

        this.hasChecked = true
        this.loading = false
        this.dialogFormVisible = true

      })
    },
    handleFileUploadSuccess(res) {
      this.form.file = res
    },
    handleImgUploadSuccess(res) {
      this.form.img = res
    },
    del(id) {
      this.request.delete("/address/" + id).then(res => {
        if (res.code === '0') {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      if (!this.multipleSelection.length) {
        this.$message.error("请选择需要删除的数据")
        return
      }
      let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
      this.request.post("/address/del/batch", ids).then(res => {
        if (res.code === '0') {
          this.$message.success("批量删除成功")
          this.load()
        } else {
          this.$message.error("批量删除失败")
        }
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    download(url) {
      window.open(url)
    },
    query() {
      this.pageNum = 1
      this.load()
    },
  }
}
</script>


<style>
.headerBg {
  background: #eee !important;
}
</style>
